<template>
  <el-upload
    class="upload-demo"
    :action="apiPath"
    :before-upload="handleBeforeUpload"
    :on-success="handleSuccess"
    :file-list="value"
    list-type="picture"
  >
    <el-button
      size="small"
      type="primary"
      style="{
        display: value.length < maxImgCount ? 'block' : 'none';
    }"
      >点击上传</el-button
    >
  </el-upload>
</template>
<script>
export default {
  props: {
    apiPath: {
      type: String,
      default: "",
    },
    maxImgCount: {
      type: Number,
      default: 4,
    },
    value: {
      default: () => {
        return [];
      },
    },
  },
  methods: {
    handleBeforeUpload(file) {
      if (this.value.length >= this.maxImgCount) {
        this.$message.error(`最多上传${this.maxImgCount}张图片`);
        return false;
      }
      const isValidFormat =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isValidFormat) {
        this.$message.error("图片必须为jpg或者png格式");
      }
      if (!isLt10M) {
        this.$message.error("图片大小不能超过10M");
      }
      return isValidFormat && isLt10M;
    },
    handleSuccess(res) {
      this.$emit("input", [...this.value, res.imageUrl]);
    },
  },
};
</script>
